package com.mobiporter.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class StringUtils {
	private static final Log log = LogFactory.getLog(StringUtils.class);

	public static String getGroup(int groupNo, String pattern, String input) {
		if (input == null || pattern == null || groupNo < 0)
			return null;

		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(input);
		if (m.find() && m.groupCount() >= groupNo) {
			return m.group(groupNo);
		} else {
			return null;
		}
	}

	public static String getStringFromInputStream(InputStream inputStream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		try {
			while ((line = reader.readLine()) != null) {
				buffer.append(line + "\n");
			}
			return buffer.toString();
		} catch (IOException e) {
			log.error("Error occured while creating string from inputStream");
		}
		return null;
	}

	public static String formatMessages(String pattern, Object... arguments) {
		return MessageFormat.format(pattern, arguments);
	}
	
	public static String formatMessagesWithUrlEncode(String pattern, Object... arguments) {
		Object[] newArgs = new Object[arguments.length];
		for (int i = 0 ; i < arguments.length;i++)
		{
			newArgs[i] = urlEncode( arguments[i]);
		}
		return MessageFormat.format(pattern, newArgs);
	}
	
	public static String urlEncode(Object toBeEncoded)
	{
		
		try 
		{
			return URLEncoder.encode(toBeEncoded.toString(),"UTF-8");
		}
		catch (UnsupportedEncodingException e) 
		{
			log.error("Encoding not supported");
			return "" ;
		}
	}

	public static String getRandomItem(String string, String delimiter) {
		if (string == null)
			return null;
		if (delimiter == null) {
			return string;
		} else if (string.indexOf(delimiter) < 0) {
			return string;
		} else {
			StringTokenizer tokenizer = new StringTokenizer(string, delimiter);
			int noOfTokens = tokenizer.countTokens();
			int index = new Random(noOfTokens).nextInt();
			for (int i = 0; i < noOfTokens; i++) {
				String token = tokenizer.nextToken();
				if (i == index) {
					return token;
				}
			}
		}
		return null;

	}
	
	

	/**
	 * Complimentary method to StringUtils.formatMap().
	 * Converts the formatted map to 
	 * actual map object.
	 * 
	 * @param toBeParsed
	 * @return
	 */
	public static Map<String,String> parseMap(String toBeParsed)
	{
		Map<String,String> map = new HashMap<String, String>();
		
		if (toBeParsed == null )
			return map ;
		if (toBeParsed.trim().equals(""))
			return map ;
		else
		{
			StringTokenizer pipeTokenizer = new StringTokenizer(toBeParsed,"|");
			while (pipeTokenizer.hasMoreTokens())
			{
				String token = pipeTokenizer.nextToken() ;
				Pattern p = Pattern.compile("(.*):(.*)");
				Matcher m = p.matcher(token);
				if (m.find() && m.groupCount() == 2)
				{
					map.put(m.group(1),m.group(2));
				}
			}
		}
			
		return map;
	}
	
	/** 
	 * Convert a map to a string, which can be thrown around
	 * in the requestParams.
	 * 
	 * @param toBeFormatted
	 * @return
	 */
	public static String formatMap(Map<String,String> toBeFormatted)
	{
		String formattedTaxString = "" ;
		if (toBeFormatted == null)
		{
			return formattedTaxString;
		}
		if (toBeFormatted.isEmpty())
		{
			return formattedTaxString ;
		}
		for (Entry<String, String> entry : toBeFormatted.entrySet())
		{
			formattedTaxString += "|"+entry.getKey()+":"+entry.getValue();
		}
		return formattedTaxString.substring(1);
	}

	public static String getItemOnIndex(String string, String delimiter,int index) 
	{
		if (string == null)
			return null ;
		
		if (delimiter == null) 
		{
			if (index >= 1)
			{
				return null ;
			}
			else
				return string ;
		} 
		else if (string.indexOf(delimiter) < 0) 
		{
			if (index >= 1)
			{
				return null ;
			}
			else
				return string ;
		} 
		else 
		{
			StringTokenizer tokenizer = new StringTokenizer(string, delimiter);
			int noOfTokens = tokenizer.countTokens();
			if (noOfTokens < index + 1)
			{
				return null ;
			}
			else
			{
				String server = null ;
				for (int i = 0; i < index+1 ; i++)
				{
					server = tokenizer.nextToken(); 
				}
				return server.trim() ;
			}
		}
	}
	
	public static boolean getBoolean(String value)
	{
		if (value==null)
       	 return false ;
        else if (value.trim().toLowerCase().equals("true"))
       	 return true ;
        else if (value.trim().toLowerCase().equals("false"))
       	 return false;
        else
       	 return false ;
	}
	
}
